<?php

namespace Modules\Admin\Http\Controllers\Subscribe;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\Common\General\Security\Api\Gateway;
use Modules\Common\Models\AdminLog;
use Modules\Common\Models\SubscriptionTypes;
use Modules\Common\Models\Members;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;
use Modules\Common\Models\Helpers\TrashManager;
use Modules\Common\Exceptions\Base\Exception;


class Delete
{

    /**
     *
     * @Route(path=/api/admin/subscribe  method=delete)
     */
    public function index()
    {

        DB::transaction(function () {

            $subscriptionTypes = SubscriptionTypes::find(request('id'));
            if ($subscriptionTypes == null) {
                Exception::new()
                    ->tellUser('订阅类型不存在')
                    ->logNotice('订阅类型不存在', ['request' => request()->all()])
                    ->throw();
            }
            //开始记录删除操作，添加至回收站
            TrashManager::startTrace(sprintf('删除订阅类型：%s', $subscriptionTypes->name));

            $membersCount = Members::where('subscription_type_id', '=', $subscriptionTypes->id)->count();

            if ($membersCount > 0) {
                Exception::new()
                    ->tellUser('已产生关联的订阅记录，不可删除')
                    ->logNotice('已产生关联的订阅记录，不可删除', ['request' => request()->all()])
                    ->throw();
            }

            // 删除操作
            $subscriptionTypes->delete();

            TrashManager::endTrace();
        });


        return Api::success();
    }
}